package com.liu.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.models.*;

/**
 * 基于阿里云的短信服务 实现短信发送封装*/
public class AliSmsUtil {

    //阿里云的key和密钥  涉及费用
    private static final String KEY="LTAI5tA9PQcCwDSCcmqyVK7S";//AccessKey ID
    private static final String KEYSECRET="QPSk1OUaFQ3MNcBO907XuUtrl3ia8J";//QPSk1OUaFQ3MNcBO907XuUtrl3ia8J
    //短信服务的签名
    public static final String SIGN="来自邢朋辉的短信";
    //短信服务的模板
    public static final String TEMCODE_VALID="SMS_115250125";//短信验证码
    public static final String TEMCODE_FIND="SMS_204975067";//找回密码验证码
    public static final String TEMCODE_NOTIFY="SMS_181550693";//短信通知

    //Sms客户端对象
    private static Client client;
    /**
     * 使用AK&SK初始化账号Client
     */
    static {
        Config config = new Config().setAccessKeyId(KEY).setAccessKeySecret(KEYSECRET);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        try {
            client= new Client(config);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
   /**
    * 发送 验证码
    * @param phone 手机号
    * @param code 验证码 */
    public static boolean sendVCode(String phone,int code){
        return sendSms(TEMCODE_VALID,phone,code);
    }
    /**
     * 发送密码找回验证码
     * @param phone 手机号
     * @param code 验证码*/
    public static boolean sendFCode(String phone,int code){
        return sendSms(TEMCODE_FIND,phone,code);
    }
    /**
     * 发送密码找回验证码
     * @param phone 手机号
     * @param name 验证码*/
    public static boolean sendMsg(String phone,String name){
        return sendSms(TEMCODE_NOTIFY,phone,name);
    }
    private static boolean sendSms(String tmcode,String phone,Object value){
        try {
            //1.创建请求对象
            SendSmsRequest request=new SendSmsRequest()
                    .setPhoneNumbers(phone)
                    .setSignName(SIGN)
                    .setTemplateCode(tmcode);
            String param="";
            //验证短信模板 模板不一样变量不一样
            if(tmcode.equals(TEMCODE_NOTIFY)){
                param="{\"name\":"+value+"}";
            }else{
                param="{\"code\":"+value+"}";
            }
            request.setTemplateParam(param);
            //3.发送请求
            SendSmsResponse response=client.sendSms(request);
            //4.验证发送结果
            if("OK".equals(response.body.getCode())){
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
